﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Utils
{
    /// <summary>
    /// 企业号推送
    /// </summary>
    public static class QYMessagePushHelper
    {
        private const string getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
        private const string sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";
        private static readonly HttpClient httpClient = new HttpClient();
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <returns></returns>
        public async static Task<string> Send(WeChatParameter parameter)
        {
            string tokenUrl = string.Format(getTokenUrl, parameter.CorpId, parameter.CorpSecret);
            var reponse = await httpClient.GetAsync(tokenUrl);
            var str = await reponse.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(str);
            var getTokenResult = jObject["errmsg"].ToString().ToLower();
            var token = jObject["access_token"].ToString();
            if (!getTokenResult.Equals("ok") || string.IsNullOrEmpty(token))
                return "获取token失败";
            string sendMsgUrl = string.Format(sendMessageUrl, token);
            var sendContentModel = new
            {
                touser = parameter.Touser,
                msgtype = parameter.MsgType,
                agentid = parameter.AgentId,
                text = new
                {
                    content = parameter.Content
                }
            };
            var sendContentStr = JsonConvert.SerializeObject(sendContentModel);
            HttpContent content = new StringContent(sendContentStr, Encoding.UTF8);
            var response = await httpClient.PostAsync(sendMsgUrl, content);
            return await response.Content.ReadAsStringAsync();
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public static void Send(string content)
        {
            var result = QYMessagePushHelper.Send(new WeChatParameter
            {
                CorpId = "ww649e974a78e5fce2",
                CorpSecret = "h67EwAk9nbB73wHTR7HxfDLtxwlXkQ1_Hp9GuvDbrFs",
                AgentId = "1000002",
                Content = content,
                Touser = "KuangJiaKangBaZi|huangchuanming|wangzhibin"
            });
        }
    }

    public class WeChatParameter
    {
        public string CorpId { get; set; }
        public string CorpSecret { get; set; }
        public string Content { get; set; }
        public string Touser { get; set; }
        public string MsgType { get; set; } = "text";
        public string AgentId { get; set; }
    }
}